﻿using System;
using Microsoft.Practices.ObjectBuilder2;

namespace MetaContainer.Unity
{
   /// <summary>
   /// A policy for crating instances using provided factory method.
   /// </summary>
   internal class FactoryMethodBuildPlanPolicy : IBuildPlanPolicy, ILifetimePolicy
   {
      private readonly Func<string, object> _factoryMethod;
      private readonly ILifetimePolicy _lifetimePolicy;

      public FactoryMethodBuildPlanPolicy(Func<string, object> factoryMethod, ILifetimePolicy lifetimePolicy)
      {
         _factoryMethod = factoryMethod;
         _lifetimePolicy = lifetimePolicy;
      }

      public void BuildUp(IBuilderContext context)
      {
         if (context.Existing == null)
         {
            string name = (string)context.Locator.Get("key");
            context.Existing = _factoryMethod(name);
         }
      }

      public object GetValue()
      {
         return _lifetimePolicy.GetValue();
      }

      public void SetValue(object newValue)
      {
         _lifetimePolicy.SetValue(newValue);
      }

      public void RemoveValue()
      {
         _lifetimePolicy.RemoveValue();
      }
   }
}
